﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using CSharp.Libs.ExceptionHandling;
using CSharp.Libs.Misc;
using CSharp.Libs.Net;

namespace CSharp.Libs.Koc
{
    public class URLItem
    {
        #region declarations
        private ExceptionCollector _EC = null;

        private String _strCommandPHP = "";
        private String _strCommandPHPPrefix = "";
        private String _strCommandPHPServerId = "";
        private String _strCommandPHPSuffix = "";
        private Dictionary<String, String> _dictParameters = null;
        private NameValueCollection _nvcParameters = null;
        private Boolean _fURLMaybeValid = false;
        #endregion



        #region constructor / terminator
        public URLItem(
            ExceptionCollector EC)
        {
            _EC = EC;
            _dictParameters = new Dictionary<String, String>();
            _nvcParameters = new NameValueCollection();
        }

        ~URLItem()
        {
            _dictParameters = null;
            _nvcParameters = null;
            _EC = null;
        }
        #endregion



        #region private functions
        private void _Reset()
        {
            try
            {
                _fURLMaybeValid = false;
                _strCommandPHP = "";
                _dictParameters.Clear();
            }
            catch (Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }
        }

        private String _GetURL()
        {
            try
            {
                String strURL = String.Concat(_strCommandPHP, "?");

                _nvcParameters.Clear();

                foreach (KeyValuePair<String, String> KVP in _dictParameters)
                {
                    _nvcParameters.Add(KVP.Key, KVP.Value);
                    strURL = String.Concat(strURL,
                        KVP.Key, "=", 
                        KVP.Value, "&");
                }

                strURL = strURL.TrimEnd('&');

                return strURL;
            }
            catch (Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }

            return "";
        }

        private String _PostURL()
        {
            try
            {
                if (_fURLMaybeValid)
                {
                    String URL = _GetURL();
                    String Answer = "";

                    if (URL != "")
                    {
                        //KocPostSubmitter KPS = new KocPostSubmitter();
                        
                        PostSubmitter PS = new PostSubmitter(_strCommandPHP);
                        PS.Type = PostSubmitter.PostTypeEnum.Post;
                        PS.PostItems = _nvcParameters;
                        Answer = PS.Post();
                        PS = null;
                    }

                    return Answer;
                }
                else
                {
                    return "<ERROR>" + this.ToString() + "." + _EC.Tools.GetCurrentMethodName() + " - URL is not valid!";
                }
            }
            catch (Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }

            return "";
        }

        private Boolean _GetAnswerHashtable(
            out Hashtable htRet)
        {
            htRet = null;

            try
            {
                String strResponse = "";
                
                strResponse = _PostURL();

                if (strResponse != "")
                {
                    htRet = JSON.JsonDecode(strResponse) as Hashtable;
                    if (htRet != null &&
                        htRet["ok"] != null)
                    {
                        if (htRet["ok"] is Boolean)
                        {
                            return (Boolean)htRet["ok"];
                        }
                        else if (htRet["ok"] is String)
                        {
                            return Boolean.Parse(htRet["ok"].ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }

            return false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="NumberString"></param>
        /// <returns></returns>
        private Boolean IsNumber(
            String NumberString)
        {
            try
            {
                Double DBL = 0;
                return Double.TryParse(NumberString, out DBL);
            }
            catch(Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }

            return false;
        }

        /// <summary>_AnalyseCommandPhp
        /// 
        /// </summary>
        /// <param name="ServerId"></param>
        /// <history>07.04.2011</history>
        private void _AnalyseCommandPhp()
        {
            try
            {
                Int32 _intStartIndex = 0;
                Int32 _intEndIndex = _strCommandPHP.IndexOf("www") + 3;

                _strCommandPHPPrefix = _strCommandPHP.Substring(_intStartIndex, _intEndIndex - _intStartIndex);

                _intStartIndex = _intEndIndex;
                _intEndIndex = _strCommandPHP.IndexOf(".", _intStartIndex);

                _strCommandPHPServerId = _strCommandPHP.Substring(_intStartIndex, _intEndIndex - _intStartIndex);

                _intStartIndex = _intEndIndex;

                _strCommandPHPSuffix = _strCommandPHP.Substring(_intStartIndex);
            }
            catch (Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }
        }

        /// <summary>_SetNewServerID
        /// 
        /// </summary>
        /// <param name="ServerId"></param>
        /// <history>07.04.2011</history>
        private void _SetNewServerID(
            Int32 ServerId)
        {
            try
            {
                if (_fURLMaybeValid &&
                    _strCommandPHPServerId != ServerId.ToString())
                {
                    _strCommandPHPServerId = ServerId.ToString();
                    _strCommandPHP = String.Concat(
                        _strCommandPHPPrefix,
                        _strCommandPHPServerId,
                        _strCommandPHPSuffix);
                }
            }
            catch (Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }
        }

        /// <summary>_GetParameterValueInt32</summary>
        /// <param name="ParameterName"></param>
        /// <returns></returns>
        /// <history>01.06.2011</history>
        private Int32 _GetParameterValueInt32(
            String ParameterKey)
        {
            try
            {
                Int32 retVal = 0;
                Int32.TryParse(_GetParameterValueString(ParameterKey), out retVal);

                return retVal;
            }
            catch (Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }

            return 0;
        }

        /// <summary>_GetParameterValueString</summary>
        /// <param name="ParameterKey"></param>
        /// <returns></returns>
        /// <history>01.06.2011</history>
        private String _GetParameterValueString(
            String ParameterKey)
        {
            try
            {
                if (_dictParameters.ContainsKey(ParameterKey))
                {
                    return _dictParameters[ParameterKey].ToString();
                }
            }
            catch (Exception ex)
            {
                _EC.AddException(ex, this.ToString(), _EC.Tools.GetCurrentMethodName());
            }

            return "";
        }
        #endregion



        #region interface
        #region properties
        public String CommandPHP
        {
            get
            {
                return _strCommandPHP;
            }
            set
            {
                _strCommandPHP = value;
                _AnalyseCommandPhp();
            }
        }

        public Int32 CommandPHPServerId
        {
            get
            {
                if (IsNumber(_strCommandPHPServerId))
                {
                    return Int32.Parse(_strCommandPHPServerId);
                }
                else
                {
                    return 0;
                }
            }
            set
            {
                if (value > 0 && value <= constants.MAX_SERVER_NUMBER)
                {
                    _SetNewServerID(value);
                }
            }
        }

        public Dictionary<String, String> Parameters
        {
            get
            {
                return _dictParameters;
            }
            set
            {
                _dictParameters = value;
            }
        }

        public Boolean URLMaybeValid
        {
            get
            {
                return _fURLMaybeValid;
            }
            set
            {
                _fURLMaybeValid = value;
            }
        }
        #endregion

        #region methods
        public void Reset()
        {
            _Reset();
        }

        public String GetURL()
        {
            return _GetURL();
        }

        public String PostURL()
        {
            return _PostURL();
        }

        public Boolean GetAnswerHashtable(
            out Hashtable htRet)
        {
            return _GetAnswerHashtable(out htRet);
        }

        public Int32 GetParameterValueInt32(
            String ParameterKey)
        {
            return _GetParameterValueInt32(ParameterKey);
        }

        public String GetParameterValueString(
            String ParameterKey)
        {
            return _GetParameterValueString(ParameterKey);
        }
        #endregion
        #endregion
    }
}
